package com.pactera.jep.service.sys.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.exception.ServiceException;
import com.pactera.jep.orm.Filter;
import com.pactera.jep.orm.Order;
import com.pactera.jep.orm.Page;
import com.pactera.jep.sys.model.Role;
import com.pactera.jep.sys.model.RoleGroupMap;
import com.pactera.jep.sys.service.RoleGroupMapService;
import com.pactera.jep.sys.service.RoleGroupService;
import com.pactera.jep.sys.service.RoleService;
import com.pactera.jep.web.code.WebCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色组关联的角色Controller
 * @author ZhangYan
 * @time 2017年5月31日 下午2:31:50
 * @company 文思海辉技术有限公司
 */
@Api(value="角色组关联角色")
@RestController
@RequestMapping("/roleGroupMap")
public class RoleGroupMapRestController extends BaseRestController<RoleGroupMap> {

	Logger logger = LoggerFactory.getLogger(RoleGroupMapRestController.class);
	
	@Autowired
	RoleGroupMapService		roleGroupMapService;
	
	@Autowired
	RoleGroupService		roleGroupService;
	
	@Autowired
	RoleService				roleService;
	
	@Override
	protected void prepareQuery(String token, Page<RoleGroupMap> page, List<Filter> filters, List<Order> orders, HttpServletRequest request) {
		
		roleGroupMapService.query(page, filters, orders);
	}

	/**
	 * 保存 - 角色组添加的角色
	 * @param jsonData
	 * @return
	 */
	@ApiOperation(value = "保存 - 角色组添加的角色")
	@PostMapping(value = "/saveRoleMap")
	public Map<String, Object> saveRoleMap(@RequestBody JSONObject jsonData){

		Map<String, Object> tips = new HashMap<String, Object>();

		try
		{
			String roleGroupCode = jsonData.getString("roleGroupCode");
			String jsonRoleList = jsonData.getString("jsonRoleList");

			/*删除已有的关联*/
			List<Filter> filters = new ArrayList<Filter>();
			filters.add(new Filter("roleGroupCode", roleGroupCode));
			roleGroupMapService.deleteByFilter(filters);
			
			/*添加新增的关联*/
			List<Role> list = JSON.parseArray(jsonRoleList, Role.class);
			roleGroupMapService.saveRoleMap(list, roleGroupCode);
			
			tips.put(WebCode.SUCCESS, true);
			tips.put(WebCode.MSG, WebCode.SUCCESS_SAVE);
		}
		catch (ServiceException e) 
		{
			logger.info(e.getMessage());
			tips.put(WebCode.SUCCESS, false);
			tips.put(WebCode.MSG, WebCode.FAILURE_SAVE);
		}
		
		return tips;
	}

}
